package com.jxmcloud.business.cut.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 该解析器能捕获到非 Controller 异常,主要是用来打印请求相关信息的
 * 优先级调到最高但是返回 null ,不拦截流程,如果需要处理的, 参考 files 工程 用 response 返回结果
 *
 * @author chengjun@whzwxxjsyxgs.wecom.work
 * @Description 全球异常解析器
 * @date 2023-02-17 03:55:08
 */
@Component
@Order(value = Ordered.HIGHEST_PRECEDENCE)
@Slf4j
public class GlobalExceptionResolver implements HandlerExceptionResolver {
    @Override
    @Nullable
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, @Nullable Object handler, Exception ex) {
        Object object = handler == null ? ex : handler;
        String osType = request.getHeader("osType");
        String osVersion = request.getHeader("osVersion");
        String msg = String.format("url = %s, hanlder = %s, osType:%s,osVersion:%s", request.getRequestURI(), object.getClass().getName(), osType, osVersion);
        if (!(ex instanceof BindException)) {
            log.error(msg, ex);
        } else {
            log.error(msg);
        }
        // 返回空的意思是接着进行默认流程,不拦截处理传递逻辑
        return null;
    }
}